package com.yixun.service.impl;

import com.alibaba.fastjson.JSON;
import com.yixun.entity.YxRoleOpt;
import com.yixun.entity.YxUser;
import com.yixun.mapper.RoleOptMapper;
import com.yixun.service.LogSetService;
import com.yixun.service.RoleOptService;
import com.yixun.util.FormatUtil;
import com.yixun.util.LogUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;


@Service
public class RoleOptServiceImpl implements RoleOptService {

    private final RoleOptMapper roleOptMapper;

    private final LogSetService logSetService;

    public RoleOptServiceImpl(RoleOptMapper roleOptMapper, LogSetService logSetService) {
        this.roleOptMapper = roleOptMapper;
        this.logSetService = logSetService;
    }


    @Override
    public String getOptIDSByRoleID(String role_id) {
        return roleOptMapper.getOptIDSByRoleID(role_id);
    }

    @Override
    @Transactional
    public int insertRoleOpt(YxUser sessionUser, Map map) {
        int row;
        String roleId = (String) map.get("role_id");
        row = roleOptMapper.delRoleOptByRoleId(roleId);
        String opt_ids = (String) map.get("opt_ids");
        if (null != opt_ids && !opt_ids.equals("")) {
            String[] optIds = opt_ids.split(",");
            YxRoleOpt roleOpt = new YxRoleOpt();
            roleOpt.setRole_id(roleId);
            for (String opt_id: optIds) {
                roleOpt.setRole_opt_id(new FormatUtil().getUUID());
                roleOpt.setOpt_id(Long.parseLong(opt_id));
                roleOptMapper.insertRoleOpt(roleOpt);
                row++;
            }
        } else {
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.ADD, "角色关联权限", JSON.toJSONString(map), sessionUser);
            return row;
        }
        return 0;
    }
}
